import 'dart:async';

import 'package:carousel_slider/carousel_slider.dart';
import 'package:chewie/chewie.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/game_detail_item.dart';
import 'package:flutter_syt/datas/game_medal_rank_model.dart';
import 'package:flutter_syt/datas/provider_index_setting.dart';
import 'package:flutter_syt/datas/user_comment_model.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/games/widget/game_user_comment.dart';
import 'package:flutter_syt/domain/news/video_controls.dart';
import 'package:flutter_syt/domain/waystation/map_helper.dart';
import 'package:flutter_syt/domain/widgets/list_item.dart';
import 'package:flutter_syt/domain/widgets/network_load_image.dart';
import 'package:flutter_syt/domain/widgets/pdf_screen.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_comment.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:flutter_syt/widgets/web_detail.dart';
import 'package:video_player/video_player.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '../../global_easy_loading.dart';

@RoutePage(name: "gameDetail")
class GameDetail extends StatefulWidget {
  final String id;
  final bool isVideo;
  final bool isVenue;

  GameDetail(this.id, {this.isVideo = false, this.isVenue = false});

  @override
  _GameDetailState createState() => _GameDetailState();
}

class _GameDetailState extends State<GameDetail> {
  //是否已结束
  bool isloading = true;
  GameDetailData? data;
  ChewieController? _chewieController;
  VideoPlayerController? _playerController;
  int videoSelected = 0;
  bool needPlay = true;
  String? error;
  // LocationData? _locationData;
  // String? _distance;
  // List<Result> resultInfos = [];
  int rankIndex = 1;
  List<GameMedalRankModel> _rankModels = [];
  bool _showFilesMore = true;
  UserCommentModel _userCommentModel = UserCommentModel(comment: []);

  final commentGlobalKey = GlobalKey<GameUserCommentState>();
  Timer? commentTimer;

  Map colorMap = {};
  @override
  void dispose() {
    needPlay = false;
    // _playerController?.pause();
    _playerController?.dispose();

    _chewieController?.dispose();
    super.dispose();
  }

  @override
  void initState() {
    _initInfo();

    ///定位测试

    // startLocation();

    super.initState();
  }

  // startLocation() async {
  //   try {
  //     LocationHelper.instance.result((LocationData event) async {
  //       if (event.location?.latitude != null) {
  //         _locationData = event;
  //       }
  //       // calculationDistance();
  //     });
  //     await LocationHelper.instance.startLocation();
  //   } catch (e) {}
  // }

  // calculationDistance() async {
  //   if (_locationData != null && data?.venue.lat != 0) {
  //     var distance = UtilsComment.getDistance(
  //         BMFCoordinate(_locationData?.location?.latitude ?? 0.0,
  //             _locationData?.location?.longitude ?? 0.0),
  //         BMFCoordinate(data?.venue.lat ?? 0.0, data?.venue.long ?? 0.0));
  //     if (mounted) {
  //       setState(() {
  //         _distance = (distance / 1000).toStringAsFixed(2);
  //       });
  //     }
  //   } else {
  //     _distance = null;
  //   }
  // }

  Widget loading() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            "assets/icons/empty.png",
            width: 80,
            height: 80,
          ),
          Container(
            height: 12,
          ),
          Text(
            S.of(context).loading,
            style:
                TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 14),
          ),
          Container(
            height: 20,
          ),
        ],
      ),
    );
  }

  Future _initVideo() async {
    if (data?.video != null) {
      try {
        if (_playerController != null) {
          await _playerController?.pause();
          await _playerController?.dispose();
          await Future.delayed(Duration(milliseconds: 50));
        }
        _playerController = VideoPlayerController.network(
            data?.video?.origin[videoSelected].url ?? "");
        await _playerController?.initialize();
        appContext.connectivitySubscription.onData((datas) async {
          appContext.connectionStatus = datas.first;
        });
        if (!needPlay) {
          return;
        }
        var isLive = false;
        if (data?.video?.video_type == "1") {
          isLive = true;
        }
        _chewieController = ChewieController(
          autoPlay: true,
          allowedScreenSleep: false,
          customControls: VideoCustomControls(null, isLive),
          deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
          videoPlayerController: _playerController!,
        );
        if (appContext.connectionStatus == ConnectivityResult.wifi) {
          // _chewieController = ChewieController(
          //   autoPlay: true,
          //   allowedScreenSleep: false,
          //   customControls: VideoCustomControls(null, isLive),
          //   deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
          //   videoPlayerController: _playerController!,
          // );
        } else {
          // _chewieController = ChewieController(
          //   autoPlay: false,
          //   allowedScreenSleep: false,
          //   customControls: VideoCustomControls(null, isLive),
          //   deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
          //   videoPlayerController: _playerController!,
          // );

          customShowToast(S.current.game_mobiledata);
        }
      } catch (e) {}
    }
    setState(() {});
  }

  Future _initInfo() async {
    setState(() {
      isloading = true;
    });
    try {
      if (widget.isVideo) {
        data = await API.shared.game.videoDetail(widget.id);
      } else {
        data = await API.shared.game.scheduleDetail(widget.id);
      }

      _getUserComment();
      // calculationDistance();
      if (!mounted) {
        return;
      }
      error = null;
      _initVideo();
    } on DioException catch (e) {
      if (e.type == DioExceptionType.unknown) {
        // error = "无网络请重试";
        error = S.current.network_error;
      } else {
        error = e.message;
      }
    } catch (e) {
      error = "$e";
    }
    // getResult();
    setState(() {
      isloading = false;
    });
  }

  _getUserComment() async {
    if (ProviderIndexSetting().indexSetting.gameComment == 1) {
      API.shared.game.getUserComments(widget.id).then((value) {
        _userCommentModel = value;
        _userCommentModel.comment?.forEach((element) {
          if (!colorMap.keys.contains(element.createTime)) {
            colorMap[element.createTime] = UtilsComment.randomColor();
          }
        });
        if (mounted) {
          setState(() {});
        }
      });
    }
  }

  // _getResult() async {
  //   List<GameMedalRankModel> rows =
  //       await API.shared.game.gameMedalRankList(rankIndex);
  //   if (rankIndex == 1) {
  //     _rankModels.clear();
  //     _rankModels = rows;
  //     if (_rankModels.isNotEmpty) {
  //       if (mounted) {
  //         setState(() {});
  //       }
  //     }
  //   } else {
  //     _rankModels.addAll(rows);
  //     if (mounted) {
  //       setState(() {});
  //     }
  //   }
  // _rankModels = await API.shared.game.gameMedalRankList(rankIndex);
  // if (_rankModels.isNotEmpty) {
  //   if (mounted) {
  //     setState(() {});
  //   }
  // }
  // if (data?.rsc != null) {
  //   try {
  //     Response response = await Dio().get(
  //         "https://results.2021chengdu.com/api/tp/result/info_list?key=9227a3c37dca4d8cab34cbed72f4c748&rsc=${data?.rsc ?? ''}");
  //     if (response.data['data'] is List) {
  //       List<GameParticipantInfo> participantInfos =
  //           ((response.data['data'] as List<dynamic>?) ?? [])
  //               .map((e) => GameParticipantInfo.fromJson(
  //                   jsonDecode(e) as Map<String, dynamic>))
  //               .toList();
  //       participantInfos.forEach((e) {
  //         if (e.odfBody?.competition?.result != null &&
  //             (e.odfBody?.competition?.result ?? []).isNotEmpty) {
  //           resultInfos.addAll(e.odfBody?.competition?.result ?? []);
  //         }
  //       });
  //       if (resultInfos.length > 2) {
  //         resultInfos.sort((left, right) =>
  //             (left.rank ?? '0').compareTo(right.rank ?? '0'));
  //       }
  //       if (mounted) {
  //         setState(() {});
  //       }
  //     }
  //   } catch (e) {}
  // }
  // }

  startComment() {
    if (commentTimer == null) {
      int comentAddIndex = 10;
      commentTimer = Timer.periodic(Duration(seconds: 1), (timer) {
        comentAddIndex = comentAddIndex - 1;
        commentGlobalKey.currentState?.updatePeriod(comentAddIndex);
        if (comentAddIndex <= 0) {
          // timer.cancel();
          commentTimer?.cancel();
          commentTimer = null;
        }
      });
    }
  }

  Widget errorBody() {
    return Center(
      child: TextButton(
        child: ViewStateEmptyWidget(
          message: error,
        ),
        onPressed: ClickUtils.debounce(() {
          _initInfo();
        }),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget body;
    if (isloading) {
      body = loading();
    } else if (error != null) {
      body = errorBody();
    } else {
      var gameData = data;
      if (gameData == null) {
        body = Container();
      } else {
        var isDone = gameData.status == "FINISHED";
        body = Container(
            margin: EdgeInsets.fromLTRB(0, 20, 0, 0),
            child: Column(
              children: [
                Expanded(
                  child: ListView(
                    padding:
                        EdgeInsets.only(left: 15.w, right: 15.w, bottom: 15.w),
                    children: [
                      Container(
                        child: Text(
                          "${gameData.discipline_name} ${gameData.name}",
                          style: TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.w600,
                            color: Color(0xff000000),
                          ),
                        ),
                      ),
                      Container(
                        height: 14,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Text(
                                '${gameData.date} ${gameData.time}',
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w400,
                                  color: ThemeColor.colorBlack60,
                                ),
                              ),
                              if (gameData.type != "2")
                                Container(
                                  margin: EdgeInsets.only(left: 10),
                                  padding: EdgeInsets.only(left: 5, right: 5),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(2),
                                      border: isDone
                                          ? null
                                          : Border.all(
                                              width: 0.5,
                                              color: Color(0x66000000),
                                            ),
                                      color: isDone
                                          ? ThemeColor.colorBlack10
                                          : Color(0xffffffff)),
                                  height: 20,
                                  alignment: Alignment.center,
                                  child: Text(
                                    gameData.status_name,
                                    style: TextStyle(
                                      fontSize: 11,
                                      fontWeight: FontWeight.w400,
                                      color: ThemeColor.colorBlack40,
                                    ),
                                  ),
                                ),
                            ],
                          ),

                          // _buildSubscribed(gameData)
                          isDone || gameData.type == "2"
                              ? Container()
                              : _buildSubscribed(gameData)
                          // Container(
                          //     alignment: Alignment.center,
                          //     padding: EdgeInsets.symmetric(horizontal: 8),
                          //     height: 24,
                          //     decoration: BoxDecoration(
                          //       color: Color(0x4cF7D749),
                          //       borderRadius: BorderRadius.circular(4),
                          //     ),
                          //     child: Text(
                          //       // ',sad',
                          //       gameData.subscribed
                          //           ? S.of(context).Subscribed
                          //           : S.of(context).Subscribe,
                          //       style: TextStyle(
                          //         fontSize: 12,
                          //         fontWeight: FontWeight.w500,
                          //         color: ThemeColor.colorBlack10,
                          //       ),
                          //     ),
                          //   )
                        ],
                      ),

                      getGameFiles(gameData.files ?? []),
                      getGameHeaderFiles(),
                      // isDone ? isDoneBox(reportData) : Container(),
                      gameVideo(),
                      videoSource(),
                      // gameJoinMember(gameData.sportsman),
                      gameGround(gameData.venue),
                      _buildCommentRows(),
                      gamePoints(),
                    ],
                  ),
                ),
                if (ProviderIndexSetting().indexSetting.gameComment != 1)
                  Container(
                    color: Color(0xFFE4E4E4),
                    height: 1,
                  ),
                _buildBottomComment()
              ],
            ));
      }
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(
          S.of(context).Details_2,
        ),
      ),
      body: body,
      // body: WillPopScope(
      //   onWillPop: () async {
      //     debugPrint("is pop ---------------  ");
      //     needPlay = false;
      //     _playerController?.pause();
      //     return true;
      //   },
      //   child: body,
      // ),
    );
  }

  Widget _buildSubscribed(GameDetailData data) {
    // if (data.status != 'FINISHED')
    return Visibility(
      visible: data.status != 'FINISHED',
      child: GestureDetector(
          onTap: ClickUtils.debounce(() async {
            if (!UserInfo.me.isLogin) {
              RouteManager.push(
                context,
                RoutMapping.loginByPwd(),
              );
              return;
            }
            if (data.subscribed) {
              try {
                await API.shared.game.cancelMatchSubscribe(data.g_id);
                data.subscribed = false;
                setState(() {});
                customShowToast(S.of(context).unsubscribe_succeeded);
              } catch (e) {
                await UtilsOther.showCustomShowError(e);
                // if (e is DioError) {
                //   customShowToast(e.message);
                // } else {
                //   customShowToast(S.of(context).network_error);
                // }
              }
            } else {
              try {
                await API.shared.game.subscribeMatch(data.g_id);
                data.subscribed = true;
                setState(() {});
              } catch (e) {
                await UtilsOther.showCustomShowError(e);
                // if (e is DioError) {
                //   customShowToast(e.message);
                // } else {
                //   customShowToast(S.of(context).network_error);
                // }
              }
            }
          }),
          child: Container(
            height: 28,
            // margin: EdgeInsets.only(bottom: 12),
            padding: EdgeInsets.symmetric(horizontal: 16),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(4)),
              color: data.subscribed
                  ? Color(0xffF7D749).withOpacity(0.3)
                  : Color(0xffF7D749),
            ),
            child: Text(
              data.subscribed ? S().Subscribed : S().Subscribe,
              maxLines: 1,
              style: TextStyle(
                color: data.subscribed
                    ? Colors.black.withOpacity(0.6)
                    : Colors.black,
                // fontWeight: FontWeight.w500,
                fontSize: 12,
              ),
            ),
          )),
    );
  }

  Widget videoSource() {
    var videoData = data?.video;
    if (videoData == null) {
      return Container();
    }
    if (videoData.origin.length == 0 || videoData.origin.length == 1) {
      return Container();
    }

    var title = "";
    if (videoData.video_type == "1") {
      title = "直播信号源";
    } else {
      title = "点播视频";
    }
    List<Widget> list = [];
    for (int i = 0; i < videoData.origin.length; i++) {
      var e = videoData.origin[i];
      var item = GestureDetector(
        child: Container(
          height: 32,
          decoration: BoxDecoration(
              color: i == videoSelected ? ThemeColor.primaryColor : Color(0xfff4f4f4),
              borderRadius: BorderRadius.all(Radius.circular(8))),
          padding: EdgeInsets.only(left: 10, right: 10),
          child: Text(
            e.name,
            style: TextStyle(
              fontSize: 14,
              color: Colors.black.withOpacity(0.6),
              height: 1.8,
            ),
          ),
        ),
        onTap: ClickUtils.debounce(() async {
          videoSelected = i;
          await _initVideo();
          setState(() {});
        }),
      );
      list.add(item);
    }

    return Container(
      margin: EdgeInsets.only(top: 26),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: Color(0xff000000),
            ),
          ),
          Container(
            height: 20,
          ),
          Wrap(
            alignment: WrapAlignment.start,
            spacing: 10,
            children: list,
          ),
        ],
      ),
    );
  }

  Widget _buildCommentRows() {
    return Visibility(
        visible: (_userCommentModel.comment ?? []).isNotEmpty,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 24.w,
            ),
            Text(
              S.current.game_likeerComment,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Color(0xff000000),
              ),
            ),

            Container(
              margin: EdgeInsets.only(top: 8.w),
              // color: Colors.red,
              height: (_userCommentModel.comment ?? []).length > 5
                  ? (64.0 * 5)
                  : (64.0 * (_userCommentModel.comment ?? []).length),
              child: (_userCommentModel.comment ?? []).length > 5
                  ? CarouselSlider(
                      options: CarouselOptions(
                          // aspectRatio: 0.2,
                          viewportFraction: 0.2,
                          autoPlay: true,
                          scrollDirection: Axis.vertical),
                      items: (_userCommentModel.comment ?? []).map((msg) {
                        // Comment e = _userCommentModel.comment![index];
                        return _buidlCommentRows(msg);
                        // return Container(
                        //   color: Colors.red[100 *
                        //       ((_userCommentModel.comment ?? []).indexOf(msg))],
                        // );
                      }).toList(),
                    )
                  : ListView.builder(
                      physics: (_userCommentModel.comment ?? []).length > 5
                          ? null
                          : NeverScrollableScrollPhysics(),
                      itemCount: (_userCommentModel.comment ?? []).length,
                      itemBuilder: (context, index) {
                        Comment e = _userCommentModel.comment![index];
                        return _buidlCommentRows(e);
                      },
                    ),
            )
            // ListView.builder(itemBuilder)
          ],
        ));
  }

  Widget _buidlCommentRows(Comment e) {
    return Container(
      height: 64,
      // color: Colors.red[(_userCommentModel.comment ?? []).indexOf(e) * 100],
      // margin: EdgeInsets.symmetric(vertical: 8.w),
      // alignment: Alignment.center,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ClipOval(
              child: Container(
            // padding: EdgeInsets.all(5),
            // color: colorMap[e.createTime],
            decoration: BoxDecoration(
                gradient: LinearGradient(
                    colors: colorMap[e.createTime],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter)),
            // child: CachedNetworkImage(
            //   imageUrl: _userCommentModel.game?.cover ?? '',
            //   fit: BoxFit.cover,
            //   width: 40.w,
            //   height: 40.w,
            // ),
            child: NetworkLoadImage.loadNetworkImage(
              _userCommentModel.game?.cover ?? '',
              width: 40.w,
              height: 40.w,
            ),
          )),
          SizedBox(
            width: 12.w,
          ),
          Expanded(
              child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                e.comment ?? '',
                style: TextStyle(
                  fontSize: 14,
                  height: 1.1,
                  color: Color(0xff000000),
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              SizedBox(
                height: 3.w,
              ),
              Text(
                e.flag ?? '',
                style: TextStyle(
                  fontSize: 12,
                  color: Color(0xff000000).withOpacity(0.4),
                ),
              )
            ],
          ))
        ],
      ),
    );
  }

  Widget gamePoints() {
    if ((data?.focus_text ?? "") == "") {
      return Container();
    }
    return Container(
      margin: EdgeInsets.only(top: 26.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Text(
            '比赛看点',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: Color(0xff000000),
            ),
          ),
          Html(
            data: data?.focus_text ?? "",
          ),
        ],
      ),
    );
  }

  Widget isDoneBox(List<ListItemEntity> data) {
    return Container(
      margin: EdgeInsets.only(top: 26.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: ThemeColor.bkColorFFFFFF,
        boxShadow: [
          BoxShadow(
            color: Color(0xffDEDEDE).withOpacity(0.5),
            blurRadius: 5.0,
            offset: Offset(3.0, 0),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: data
            .map((e) => GestureDetector(
                  onTap: ClickUtils.debounce(() => e.onTap),
                  child: Container(
                      // color: Colors.blueGrey,
                      alignment: Alignment.center,
                      child: ListItem(e)),
                ))
            .toList(),
      ),
    );
  }

  // Widget gameJoinMember(List sportsMan) {
  //   if (_rankModels.length == 0) {
  //     return Container();
  //   }
  //   return Container(
  //     margin: EdgeInsets.only(top: 26.0),
  //     child: Column(
  //       crossAxisAlignment: CrossAxisAlignment.start,
  //       mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  //       children: [
  //         Row(
  //           mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //           children: [
  //             Text(
  //               S().game_participant,
  //               style: TextStyle(
  //                 fontSize: 16,
  //                 fontWeight: FontWeight.w600,
  //                 color: Color(0xff000000),
  //               ),
  //             ),
  //             Text(
  //               (_rankModels.length > 2 ? S().game_ranking : S().game_score),
  //               style: TextStyle(
  //                 fontSize: 16,
  //                 fontWeight: FontWeight.w600,
  //                 color: Color(0xff000000),
  //               ),
  //             ),
  //           ],
  //         ),
  //         ..._rankModels.map((item) {
  //           return iconName(item);
  //         }).toList(),
  //         Visibility(
  //             visible: _rankModels.length % 15 == 0,
  //             child: Row(
  //               mainAxisAlignment: MainAxisAlignment.center,
  //               children: [
  //                 GestureDetector(
  //                   onTap: () {
  //                     rankIndex++;
  //                     // getResult();
  //                   },
  //                   child: Container(
  //                     margin: EdgeInsets.only(top: 10),
  //                     height: 22,
  //                     padding: EdgeInsets.symmetric(horizontal: 14),
  //                     decoration: BoxDecoration(
  //                       borderRadius: BorderRadius.circular(11),
  //                       border: Border.all(
  //                           width: 0.5, color: Colors.black.withOpacity(0.4)),
  //                     ),
  //                     alignment: Alignment.center,
  //                     child: Text(
  //                       S().game_more,
  //                       style: TextStyle(
  //                           fontSize: 12, color: Colors.black.withOpacity(0.4)),
  //                     ),
  //                   ),
  //                 )
  //               ],
  //             ))
  //         // return Container();
  //         // }).toList(),
  //       ],
  //     ),
  //   );
  // }

  Widget iconName(GameMedalRankModel model) {
    return Container(
      margin: EdgeInsets.only(top: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          NetworkLoadImage.loadNetworkImage(model.nationalFlag,
              width: 15.w, height: 10.w),
          // Image.asset(
          //   'assets/images/game_member.png',
          //   width: 32,
          // ),
          Container(
            width: 12,
          ),
          Text(
            model.name ?? '',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w400,
              color: ThemeColor.colorBlack80,
            ),
          ),
          Expanded(child: Container()),
          Text(
            (model.rankequal == 'Y' ? '=' : '') + (model.rank ?? '').toString(),
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w400,
              color: ThemeColor.colorBlack80,
            ),
          ),
        ],
      ),
    );
  }

  Widget gameVideo() {
    Widget video = Container();
    var real = data?.video;
    if (real == null) {
      return video;
    }
    if (data?.video_status == "0") {
      video = Container(
        padding: EdgeInsets.only(top: 20),
        child: AspectRatio(
          aspectRatio: 16 / 9,
          child: Container(
            color: Colors.black,
            child: Center(
              child: Flexible(
                child: Text(
                  data?.video_status_name ?? "",
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        ),
      );
    } else if (_playerController != null && _chewieController != null) {
      video = Container(
        padding: EdgeInsets.only(top: 20),
        child: AspectRatio(
          aspectRatio: 16 / 9,
          child: Chewie(
            controller: _chewieController!,
          ),
        ),
      );
    } else if (real.origin.length > 0) {
      video = Container(
        padding: EdgeInsets.only(top: 20),
        child: AspectRatio(
          aspectRatio: 16 / 9,
          child: Container(
            color: Colors.black,
          ),
        ),
      );
    }
    return video;
  }

  Widget getGameHeaderFiles() {
    return Visibility(
        visible: data?.gameUrl != null && (data?.gameUrl ?? '').isNotEmpty,
        child: GestureDetector(
          onTap: ClickUtils.debounce(() {
            var web = WebDetailPage(data?.gameUrl ?? '');
            web.needBar = true;
            // web.needLongpressSave = false;
            Navigator.of(context).push(MaterialPageRoute(
                builder: (context) => web,
                settings: RouteSettings(name: "web_detail", arguments: "")));
          }),
          child: Container(
            height: 72.w,
            padding: EdgeInsets.symmetric(horizontal: 12),
            margin: EdgeInsets.only(top: 12),
            decoration: BoxDecoration(
                image: DecorationImage(
              image: AssetImage(
                'assets/images/game_info_check_bg.png',
              ),
              fit: BoxFit.cover,
            )),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  // constraints: BoxConstraints(maxWidth: 260.w),
                  child: Text(
                    S.current.game_check_more,
                    style: TextStyle(
                        color: Color(0xff111111),
                        fontSize: 14,
                        fontWeight: FontWeight.w500),
                  ),
                ),
                SizedBox(
                  height: 4,
                ),
                Container(
                  // constraints: BoxConstraints(maxWidth: 260.w),
                  child: Row(
                    children: [
                      Text(
                        S.current.game_click_check,
                        style: TextStyle(
                            color: Color(0xff111111).withOpacity(0.6),
                            fontSize: 12),
                      ),
                      SizedBox(
                        width: 4,
                      ),
                      Image.asset(
                        'assets/images/game_info_check_arrow.png',
                        width: 6,
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  Widget getGameFiles(List<GameFilesModel> files) {
    return Visibility(
        visible: files.isNotEmpty,
        child: Container(
          margin: EdgeInsets.only(
            top: 12,
          ),
          padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
          width: double.infinity,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: Color(0xffF7F7F7),
          ),
          child: Column(
            children: [
              ...((files.length > 5 && _showFilesMore)
                      ? files.sublist(0, 5)
                      : files)
                  .map((e) {
                return GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: ClickUtils.debounce(() {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => PDFScreen(
                                  e.file_path ?? '',
                                  title: e.name ?? '',
                                )));
                  }),
                  child: Container(
                    height: 41,
                    child: Row(
                      children: [
                        Image.asset(
                          'assets/images/game_files.png',
                          width: 20,
                          height: 20,
                        ),
                        SizedBox(
                          width: 6,
                        ),
                        Expanded(
                            child: Text(
                          e.name ?? '',
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                          style: TextStyle(color: Colors.black, fontSize: 14),
                        )),
                        Image.asset(
                          'assets/icons/icon_right.png',
                          width: 5,
                          height: 9,
                          color: Colors.black,
                        )
                      ],
                    ),
                  ),
                );
              }).toList(),
              Visibility(
                  visible: files.length > 5 && _showFilesMore,
                  child: GestureDetector(
                    onTap: ClickUtils.debounce(() {
                      if (mounted) {
                        setState(() {
                          _showFilesMore = false;
                        });
                      }
                    }),
                    child: Container(
                      margin: EdgeInsets.only(bottom: 20),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            S.current.game_more,
                            style: TextStyle(
                                color: Colors.black.withOpacity(0.6),
                                fontSize: 12),
                          ),
                          Icon(
                            Icons.keyboard_arrow_down,
                            color: Colors.black.withOpacity(0.6),
                            size: 16,
                          )
                        ],
                      ),
                    ),
                  ))
            ],
          ),
        ));
  }

  Widget _buildBottomComment() {
    if (ProviderIndexSetting().indexSetting.gameComment != 1) {
      return Container();
    }
    return GestureDetector(
      onTap: ClickUtils.debounce(() {
        if (UserInfo.me.isLogin) {
          showModalBottomSheet(
            backgroundColor: Colors.transparent,
            context: context,
            isScrollControlled: true,
            builder: (context) {
              return GameUserComment(
                id: widget.id,
                key: commentGlobalKey,
              );
            },
          ).then((value) {
            if (value is bool) {
              customShowToast(
                  value ? S.current.game_sendSuccess : S.current.game_sendFail);
              if (value) {
                startComment();
                _getUserComment();
              }
            }
          });
        } else {
          RouteManager.push(
            context,
            RoutMapping.loginByPwd(),
          );
        }
      }),
      child: Container(
        height: 40,
        margin: EdgeInsets.only(
            left: 15.w,
            right: 15.w,
            top: 5.w,
            bottom: ScreenUtil().bottomBarHeight + 5.w),
        decoration: BoxDecoration(
          color: ThemeColor.primaryColor,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Center(
          child: Text(
            S.current.game_meComment,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: ThemeColor.colorBlack100,
            ),
          ),
        ),
      ),
    );
  }

  Widget gameGround(GameDetailDataVenue venue) {
    // var size = MediaQuery.of(context).size;

    return Container(
      // decoration:
      // BoxDecoration(border: Border.all(color: Color(0xffE4E4E4), width: 1)),
      // margin: EdgeInsets.only(top: 26.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          // Container(
          //   height: 10,
          // ),
          // Text(
          //   S.of(context).Venue,
          //   style: TextStyle(
          //     fontSize: 16,
          //     fontWeight: FontWeight.w600,
          //     color: Color(0xff000000),
          //   ),
          // ),
          GestureDetector(
            onTap: ClickUtils.debounce(() {
              if (widget.isVenue) {
                // _playerController?.pause();
                Navigator.pop(context);
              } else {
                if (venue.type != 2) {
                  _playerController?.pause();
                  RouteManager.push(
                    context,
                    RoutMapping.venueDetailPage(venue.id),
                  ).then((value) {
                    _playerController?.play();
                  });
                }
              }
            }),
            child: Container(
              margin: EdgeInsets.only(top: 24),
              padding: EdgeInsets.fromLTRB(15, 12, 16, 12),
              width: double.infinity,
              decoration: BoxDecoration(
                  border: Border.all(color: Color(0xffE4E4E4), width: 1),
                  borderRadius: BorderRadius.circular(8),
                  image: DecorationImage(
                    image: AssetImage(
                      'assets/images/game_map_bg.png',
                    ),
                    fit: BoxFit.cover,
                  )),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Row(
                      children: [
                        // Image.asset(
                        //   'assets/images/game_member.png',
                        //   width: 40,
                        //   height: 40,
                        // ),
                        // Container(
                        //   width: 15,
                        // ),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                venue.name,
                                softWrap: true,
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold,
                                  color: Color(0xff111111),
                                ),
                              ),
                              SizedBox(
                                height: 4,
                              ),
                              Text(
                                venue.address,
                                softWrap: true,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Color(0xff666666),
                                ),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                              Visibility(
                                visible: venue.type != 2,
                                child: Container(
                                  margin: EdgeInsets.only(top: 8),
                                  child: Text(
                                    '${S.of(context).There_are}${venue.game_count} ${S.of(context).games}   >',
                                    style: TextStyle(
                                      fontSize: 10,
                                      color: Color(0xff2942D1),
                                    ),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  // Container(
                  //   width: 1,
                  //   color: Colors.black.withOpacity(0.2),
                  //   height: 50,
                  //   margin: EdgeInsets.symmetric(horizontal: 10),
                  // ),
                  // GestureDetector(
                  //     onTap: ClickUtils.debounce(() {
                  //       MapNavigatorUtil.showBottom(context,
                  //           latitude: (data?.venue.lat ?? 0.0).toString(),
                  //           longitude: (data?.venue.long ?? 0.0).toString());
                  //     }),
                  //     behavior: HitTestBehavior.opaque,
                  //     child: Column(
                  //       mainAxisAlignment: MainAxisAlignment.center,
                  //       children: [
                  //         Image.asset(
                  //           'assets/images/game_map.png',
                  //           width: 28.w,
                  //           height: 28.w,
                  //         ),
                  //         // Container(
                  //         //   height: 5,
                  //         // ),
                  //         Text(
                  //           '${_distance ?? "-"}km',
                  //           style: TextStyle(
                  //             fontSize: 12,
                  //             color: ThemeColor.colorBlack60,
                  //           ),
                  //         ),
                  //       ],
                  //     ))
                ],
              ),
            ),
          ),
          // Container(
          //   width: double.infinity,
          //   height: 174,
          //   margin: EdgeInsets.only(top: 12),
          //   child: MapPage(
          //     markers: [
          //       MarkerEntity()
          //         ..name = venue.name
          //         ..lat = venue.lat
          //         ..long = venue.long
          //         ..address = venue.address
          //         ..id = venue.id
          //         ..icon = "assets/icons/icon_arch_current.png"
          //     ],
          //     locationCenter: false,
          //     markerCenter: true,
          //     showPanel: false,
          //     size: MapSize()
          //       ..width = size.width
          //       ..height = 174,
          //     needRoute: false,
          //   ),
          // )
        ],
      ),
    );
  }
}
